
package cn.tang.tframe.sdm.web.filter;

import cn.tang.tframe.common.utils.lang.StringUtils;
import cn.tang.tframe.dynconfig.CommonDynConfig;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 跨域操作拦截器（在服务器返回信息后处理） <p/>
 */
public class CrossFilter extends OncePerRequestFilter {

	@Override
	protected void doFilterInternal(
		HttpServletRequest request, HttpServletResponse response,
		FilterChain filterChain)
		throws ServletException, IOException {
		String crossOrigin = CommonDynConfig.getValue("crossOrigin", "*");
		String origin = request.getHeader("Origin");
		if(StringUtils.isNotBlank(origin) && StringUtils.isNotBlank(crossOrigin)){
			if(crossOrigin.equals("*") || crossOrigin.indexOf(origin) != -1){
				response.setHeader("Access-Control-Allow-Origin", origin);
			}
		}
		response.setHeader("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");
		response.setHeader("Access-Control-Expose-Headers", "X-Requested-With");
		response.setHeader(
			"Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
		response.setHeader(
			"Access-Control-Request-Method", "POST, GET, OPTIONS, DELETE");
		response.setHeader("Access-Control-Max-Age", "3600");

//		response.setHeader("Access-Control-Allow-Headers", "Content-Type");
		response.addHeader("Access-Control-Allow-Credentials", "true");
		filterChain.doFilter(request, response);
	}
}
